package cn.oi.book.pro.controller;

import cn.oi.book.pro.model.Knowledge;
import cn.oi.book.pro.service.KnowledgeService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final KnowledgeService service;

    @GetMapping("/login")
    public String loginPage() { return "login"; }

    @GetMapping("/articles")
    public String list(@RequestParam(value = "q", required = false) String q,
                       @RequestParam(value = "page", defaultValue = "0") int page,
                       @RequestParam(value = "size", defaultValue = "10") int size,
                       Model model) {
        Page<Knowledge> p = service.search(q, page, size);
        model.addAttribute("q", q);
        model.addAttribute("page", p);
        return "admin/list";
    }

    @GetMapping({"/article/new", "/article/{id}"})
    public String form(@PathVariable(required = false) Long id, Model model) {
        Knowledge k = (id == null) ? new Knowledge() : service.findById(id).orElse(new Knowledge());
        model.addAttribute("item", k);
        return "admin/form";
    }

    @PostMapping("/article")
    public String save(@ModelAttribute("item") Knowledge k, BindingResult br) {
        if (br.hasErrors()) {
            return "admin/form";
        }
        service.save(k);
        return "redirect:/admin/articles";
    }

    @PostMapping("/article/{id}/delete")
    public String delete(@PathVariable Long id) {
        service.delete(id);
        return "redirect:/admin/articles";
    }
}
